package arch.dao.impl.user;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import arch.dao.impl.user.mapper.DeptMapper;
import arch.dao.user.DeptDao;
import arch.domain.user.Dept;
/**
 * 
 * @author ZhaoWangLong Sep 4, 2012
 *
 */
@Repository("deptDao")
public class DeptImpl implements DeptDao {
	@Resource private JdbcTemplate jdbcTemplate;
	private final Logger logger = Logger.getLogger(DeptImpl.class);
	
	public Integer queryCount(String sql, Object... objects) {
		return this.jdbcTemplate.queryForInt(sql,objects);
	}

	@SuppressWarnings("unchecked")
	public List<Dept> queryList(String sql, boolean parent, Object... objects) {
		logger.debug("SQL >"+sql );
		
		return this.jdbcTemplate.query(sql, objects, new DeptMapper(parent));
	}

	public Dept find(Serializable primaryKey) {
		String sql = "select DEPT_ID, DEPT_CODE, DEPT_NAME, SORT_INDEX, PARENT, "
			+" IS_DELETE, CREATE_TIME, LAST_UPDATE_TIME from ID_DEPT where DEPT_ID = ? ";
		
		try {
			return (Dept)this.jdbcTemplate.queryForObject(sql, new Object[]{primaryKey}, new DeptMapper(false));
		}catch (EmptyResultDataAccessException e) {
			return null;
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void merge(Dept entity) {
		String sql = "update ID_DEPT set DEPT_CODE = ? , DEPT_NAME = ?, SORT_INDEX = ?, PARENT = ?, "
			+" IS_DELETE = ?, LAST_UPDATE_TIME = ? where DEPT_ID = ?"; 
		
		this.jdbcTemplate.update(sql,new Object[]{
				entity.getDeptCode(),
				entity.getDeptName(),
				entity.getSortIndex(),
				entity.getParent()==null?null:entity.getParent().getDeptId(),
				entity.isDelete()?"1":"0",
				entity.getLastUpdateTime(),
				entity.getDeptId()
		});
	}

	public void persist(Dept entity) {
		String sql = "insert into ID_DEPT (DEPT_ID, DEPT_CODE, DEPT_NAME, SORT_INDEX, PARENT,"
			+"IS_DELETE, CREATE_TIME, LAST_UPDATE_TIME) values (?,?,?,?,?,?,?,?) ";
		
		this.jdbcTemplate.update(sql,new Object[]{
				entity.getDeptId(),
				entity.getDeptCode(),
				entity.getDeptName(),
				entity.getSortIndex(),
				entity.getParent()==null?null:entity.getParent().getDeptId(),
				entity.isDelete()?"1":"0",
				entity.getCreateTime(),
				entity.getLastUpdateTime()
		});
	}

	public void remove(Serializable primaryKey) {
		String sql = "update ID_DEPT set IS_DELETE = ? where DEPT_ID = ? ";
	
		this.jdbcTemplate.update(sql,new Object[]{"1",primaryKey});
	}

}
